package org.marcesher.blogcodeformatter.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.marcesher.blogcodeformatter.formatters.UnIndentFormatter;
public abstract class TextSelectionHandler extends AbstractHandler {
	
	IResource resource = null;
	ITextSelection selection = null;
	String input, fileName, extension = "";
	
	public TextSelectionHandler() {		
	}
	
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IEditorPart editorPart = HandlerUtil.getActiveEditor(event);
		setSelection(editorPart);	
		resource = ((IResource)editorPart.getEditorInput().getAdapter(IResource.class));
		fileName = resource.getName();
		extension = resource.getFileExtension();		
		input = new UnIndentFormatter().format(selection.getText(), fileName, extension);
		
		formatInput();
		
		System.out.println(input);
		copyToClipboard(editorPart);
		return null;
	}

	/**
	 * @param editorPart
	 */
	private void setSelection(IEditorPart editorPart) {
		if(editorPart instanceof ITextEditor){
			ITextEditor editor = (ITextEditor)editorPart;
			selection = (ITextSelection) editor.getSelectionProvider().getSelection();
		}else if( editorPart instanceof MultiPageEditorPart){
			//this would be the case for the "source" mode in XML editor
			selection = (ITextSelection) editorPart.getEditorSite().getSelectionProvider().getSelection();
		}
	}

	/**
	 * @param clipboard
	 */
	private void copyToClipboard(IEditorPart editorPart) {
		Clipboard clipboard = new Clipboard(editorPart.getSite().getShell().getDisplay());
		TextTransfer textTransfer = TextTransfer.getInstance();
		clipboard.setContents(new Object[] {input.trim()}, new Transfer[]{textTransfer});		
		try {
			clipboard.dispose();
		} catch (Exception e) {
			System.out.println("Error disposing clipboard");
			System.out.println(e);
		}
	}
	
	protected abstract void formatInput();
}
